package org.twndmv.ejb;

import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This issues messages to a specified destination. You can use many of the 
 * properties to control the content of the message.
 *
 */
public class DMVPublisher {
    private static final Log log = LogFactory.getLog(DMVPublisher.class);
    protected ConnectionFactory connFactory;
    protected Destination destination;
    protected boolean stop = false;
    protected boolean stopped = false;
    protected boolean started = false;
    protected int count=0;
    protected String name;
    protected long sleepTime=10000;
    protected int maxCount=10;
    protected String username;
    protected String password;
        
    public DMVPublisher(String name) {
        this.name = name;
    }
    public void setConnFactory(ConnectionFactory connFactory) {
        this.connFactory = connFactory; 
    }
    public void setDestination(Destination destination) {
        this.destination = destination;
    }    
    public int getCount() {
        return count;
    }
    public void setSleepTime(long sleepTime) {
        this.sleepTime = sleepTime;
    }
    public void clearMessages() {
        count = 0;
    }
    public void stop() {
        this.stop = true;
    }
    public boolean isStopped() {
        return stopped;
    }
    public boolean isStarted() {
        return started;
    }
    public void setUsername(String username) {
		this.username = username;
	}
    public void setPassword(String password) {
		this.password = password;
	}
    
    public void publishDMVChange(Session session, Destination dest, String firstName, String middleName, String lastName) throws Exception {
        MessageProducer producer = null;
        try {
            producer = session.createProducer(dest);

            log.info("publisher " + name + " sending DMV person: " + firstName + " " + middleName + " " + lastName);
          
                Message message = session.createMessage();
                message.setStringProperty("firstName", firstName);
                message.setStringProperty("middleName", middleName);
                message.setStringProperty("lastName", lastName);
                producer.send(message);
                log.debug("published message(" + firstName + " " + middleName + " " + lastName + "):" + 
                        message.getJMSMessageID());
                Thread.sleep(sleepTime);
                count++;
        } 
        finally {
            if (producer != null)   { producer.close(); }
        }
    }

}
